<script setup lang="ts">
import { uploadAPI } from '@/apis/common';
import { createRentAPI, delEnterpriseAPI, delRentAPI, getEnterpriseListAPI, getRentBuildListAPI, getRentListAPI, outRentAPI } from '@/apis/enterprise';
import type { Datum, Enterprise, EnterpriseListParams, RentBuilding, RentParams } from '@/types/enterprise';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules, type UploadRawFile, type UploadRequestOptions, type UploadUserFile } from 'element-plus';
import { onMounted, ref, watch } from 'vue';

const params = ref<EnterpriseListParams>({
  name: '',
  page: 1,
  pageSize: 10
})

// 前端自定义类型，为了给每行加上合同数据
interface EnterpriseWithRent extends Enterprise {
  rentList: Datum[]
}

// 大表格数据
const list = ref<EnterpriseWithRent[]>([])
const total = ref(0)
// 获取列表
const getList = async() =>{
  const res = await getEnterpriseListAPI(params.value)
  console.log('res',res)
  list.value = res.data.rows.map(item =>({
    ...item,
    rentList: []
  }))
  total.value = res.data.total
} 
onMounted(() => {
  getList()
})
const onSearch = () => {
  params.value.page = 1
  getList()
}

// 删除企业
const delEnterprise = async(id: string) => {
  ElMessageBox.confirm('此操作将永久删除, 是否继续?', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async() => {
    // 删除
    await delEnterpriseAPI(id)
    ElMessage.success('删除成功')
    getList()
  }).catch(() => {})
}


// --------------- 添加合同 ---------------

const initRentForm = () => {
  return {
  buildingId: undefined,
  contractId: undefined,
  contractUrl: '',
  endTime: '',
  enterpriseId: undefined,
  startTime: '',
  type: 0
}
}

const rentForm = ref<RentParams>(initRentForm())
const rentRules = ref<FormRules<RentParams>>({
  buildingId: [
    { required: true, message: '请选择楼宇', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择租赁日期', trigger: 'blur' }
  ],
  contractId: [
    { required: true, message: '请上传合同文件' }
  ]
})
// 可租赁楼宇列表
const buildList = ref<RentBuilding[]>([]) 
// dialog弹窗控件
const rentDialogVisible = ref(false)
// 打开弹窗
const addRent = async(id: number) => {
  rentDialogVisible.value = true
  const res = await getRentBuildListAPI()
  // console.log('res', res);
  buildList.value = res.data
  rentForm.value.enterpriseId = id
}
// 绑定关闭弹窗的事件
const closeRent = () => {
  // 关闭弹窗
  rentDialogVisible.value = false
  // 重置表单绑定的值和校验规则
  addFormRef.value?.resetFields()
  // 重置时间数组
  timeArr.value = []
  // 重置文件列表
  fileList.value = []
  // 重置表单所有数据
  rentForm.value = initRentForm()
}
// 禁用日期的范围
const disableDate = (time: Date) => {
  return time.getTime() < Date.now() - 8.64e7
}
// 时间数组
const timeArr = ref<string[]>([])
watch(timeArr,(val)=>{
  if(val){
    rentForm.value.startTime = val[0]
    rentForm.value.endTime = val[1]
  }else{
    rentForm.value.startTime = ''
    rentForm.value.endTime = ''
  }
},{deep: true})
// 表单实例
const addFormRef = ref<FormInstance>()
// 上传文件
const onUploadContract = async (options: UploadRequestOptions) => {
  const fd = new FormData()
  fd.append('file', options.file)
  fd.append('type', 'contract')
  const res =  await uploadAPI(fd)
  console.log('contract',res)
  rentForm.value.contractUrl = res.data.url
  rentForm.value.contractId = res.data.id
  addFormRef.value?.validateField('contractId')
  return res.data.url
}
// 删除上传的合同
const removeContract = () => {
  rentForm.value.contractUrl = ''
  rentForm.value.contractId = undefined
  addFormRef.value?.validateField('contractId')
}
// 限制上传大小
const beforeUpload = (rawFile: UploadRawFile) => {
  const isLt5M = rawFile.size / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('上传图片大小不能超过5M')
    return false
  } else {
    return true
  }
}
// 文件列表
const fileList = ref<UploadUserFile[]>([])
// 提交表单
const rentSubmit = async() => {
   try {
    // 表单校验
    await addFormRef.value?.validate()
    // 提交表单
    await createRentAPI(rentForm.value)
    // 提示用户
    ElMessage.success('添加成功')
    // 关闭弹窗
    closeRent()
   }catch {
   }
}
// 展开行触发时候
const onExpandChange = async (row: EnterpriseWithRent) => {
  console.log('当前行被展开', row.id);
  // 获取展开行的合同列表
  const res = await getRentListAPI(row.id)
  console.log('rentlist', res)
  row.rentList = res.data
}
// 删除合同
const delRent = (sonRow: Datum,row: EnterpriseWithRent) =>{
  ElMessageBox.confirm('此操作将永久删除, 是否继续?', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async() => {
    // console.log('id', id)
    // 后端接口删除
    await delRentAPI(sonRow.id)
    // 前端过滤，为了不整个刷新列表，这样性能高
    row.rentList = row.rentList.filter(item => item.id !== sonRow.id)
    ElMessage.success('删除成功')
  }).catch(() => {})
} 
// 退租
const outRent = (row: Datum) => {
  ElMessageBox.confirm('此操作将永久删除, 是否继续?', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async() => {
    console.log('id', row.id)
    await outRentAPI(row.id)
    row.status = 3
    ElMessage.success('退租成功')
  }).catch(() => {})
}

</script>

<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input v-model="params.name" clearable placeholder="请输入内容" @clear="onSearch" class="search-main" />
      <el-button @click="onSearch" type="primary">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="$router.push('/exterpriseAdd')">添加企业</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="list" @expand-change="onExpandChange" row-key="id">
        <!-- type="expand" 显示一个可展开的按钮 -->
        <el-table-column type="expand">
          <template #default="{ row }">
            <el-table :data="row.rentList">
              <el-table-column label="租赁楼宇" width="320" prop="buildingName" />
              <el-table-column label="租赁起始时间" prop="startTime" />
              <el-table-column label="合同状态" prop="status">
                <template #default="scope">
                  <el-tag v-if="scope.row.status === 0" type="warning">待生效</el-tag>
                  <el-tag v-else-if="scope.row.status === 1" type="success">生效中</el-tag>
                  <el-tag v-else-if="scope.row.status === 2" type="info">已到期</el-tag>
                  <el-tag v-else-if="scope.row.status === 3" type="danger">已退租</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="280">
                <template #default="{ row: sonRow }">
                  <el-button size="small" type="primary" link>续租</el-button>
                  <el-button size="small" @click="outRent(sonRow)" type="primary" link :disabled="sonRow.status === 3">退租</el-button>
                  <el-button size="small" @click="delRent(sonRow, row)" type="primary" link :disabled="sonRow.status !== 3">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="120" />
        <el-table-column prop="name" label="企业名称" width="320" />
        <el-table-column prop="contact" label="联系人" />
        <el-table-column prop="contactNumber" label="联系电话" />
        <el-table-column label="操作" width="300" >
          <template #default="scope">
            <el-button size="small" type="primary" @click="addRent(scope.row.id)">添加合同</el-button>
            <el-button size="small" type="primary" @click="$router.push(`/exterpriseDetail/${ scope.row.id }`)">查看</el-button>
            <el-button size="small" @click="$router.push(`/exterpriseAdd/${scope.row.id}`)" type="primary">编辑</el-button>
            <el-button size="small" type="danger" 
            :disabled="scope.row.existContractFlag"
            @click="delEnterprise(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination 
      :total="total" 
      layout="total,sizes, prev, pager, next, jumper" 
      :page-sizes="[2, 5, 10, 20]"
      v-model:page-size="params.pageSize"
      v-model:current-page="params.page"
      @change="getList()"
      />
    </div>
    <el-dialog title="添加合同" width="600px" v-model="rentDialogVisible" @close="closeRent">
      {{ timeArr }}
      <div class="form-container">
        <el-form ref="addFormRef" :model="rentForm" :rules="rentRules" label-position="top">
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select v-model="rentForm.buildingId" placeholder="请选择租赁楼宇" clearable>
              <el-option v-for="item in buildList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="租赁起止日期" prop="endTime">
            <el-date-picker :disabled-date="disableDate" v-model="timeArr" type="daterange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" value-format="YYYY-MM-DD" />
          </el-form-item>
          <el-form-item label="租赁合同" prop="contractId">
            <el-upload 
            accept=".doc, .pdf"
            :http-request="onUploadContract"
            :on-remove="removeContract"
            :before-upload="beforeUpload"
            v-model:file-list="fileList"
            >
              <el-button size="small" type="primary" plain>上传合同文件</el-button>
              <template #tip>
                <div class="el-upload__tip">支持扩展名：.doc .pdf, 文件大小不超过5M</div>
              </template>
            </el-upload>
          </el-form-item>
          {{ rentForm }}
        </el-form>
      </div>

      <template #footer>
        <div class="dialog-footer">
           <el-button size="small" @click="closeRent">取 消</el-button>
           <el-button size="small" @click="rentSubmit" type="primary">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.building-container {
  padding: 20px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>